<?php

namespace Account\Controller;

use Common\Controller\ApiController;
use Util\ModelUtils;

class MessageController extends ApiController {

    public function index() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $condition = [];
        D('MessageBox')->pickGlobalMessage($this->user['id']);
        $condition['user_id'] = $this->user['id'];
//        $condition['is_read'] = 0;
        $count = D('MessageBox')->where($condition)->cache(30)->count();

        if ($count > 0) {
            $msgs = D('MessageBox')
                    ->where($condition)
                    ->cache(30)
                    ->select();
            // ->getField('msg_id', true);
            $msgIds = array_column($msgs, 'msg_id');
            $msgDict = array_column($msgs, null, 'msg_id');
            $messages = D('Message')
                    ->where(['id' => ['in', $msgIds]])
                    ->cache(30)
                    ->order('create_time desc')
                    ->page($page, $perPage)
                    ->select();
            foreach ($messages as &$message) {
                $message['is_read'] = $msgDict[$message['id']]['is_read'];
            }
            // 全部标记为已读
            D('MessageBox')->where(['user_id' => $this->user['id'], 'is_read' => '0'])->setField('is_read', 1);
        } else {
            $messages = [];
        }
        $messages = transform('Message', 'listView', $messages);
        $pagination = pagination($count, $perPage, $page);
        $this->response($messages, $pagination);
    }

    public function detailShow($id) {
        $mbox = D('MessageBox')->where(['user_id' => $this->user['id'], 'msg_id' => $id])->find();
        if ($mbox) {
            $message = D('Message')->find($id);
            if ($message) {
                D('MessageBox')->where(['id' => $mbox['id']])->setField('is_read', 1);
                $message = transform('Message', 'detail', $message);
                $message['content'] = html_entity_decode($message['content']);
                $this->response($message);
            } else {
                $this->errorResponse(50001);
            }
        } else {
            $this->errorResponse(10010);
        }
    }

}
